package com.example.amap.gaode.search

import android.content.Context
import com.alibaba.android.arouter.facade.annotation.Route
import com.amap.api.services.help.Inputtips
import com.amap.api.services.help.Inputtips.InputtipsListener
import com.amap.api.services.help.InputtipsQuery
import com.amap.api.services.help.Tip
import com.example.amap.lib.base.utils.LogUtil
import com.example.amap.search.bean.SearchSuggestInfo
import com.example.amap.search.observer.ISearchObserver
import com.example.amap.service.ISearchService
import java.lang.ref.WeakReference

@Route(path = "/search/gaode/SearchServiceImpl")
class SearchServiceImpl : ISearchService, InputtipsListener {
    companion object {
        private const val TAG = "SearchServiceImpl"
    }

    private lateinit var contextWeakReference: WeakReference<Context>

    private val observers = mutableSetOf<ISearchObserver>()

    override fun init(context: Context?) {
        contextWeakReference = WeakReference(context)
    }

    override fun addSearchObserver(observer: ISearchObserver) {
        LogUtil.d(TAG, "addSearchObserver observer: $observer")
        observers.add(observer)
    }

    override fun removeSearchObserver(observer: ISearchObserver) {
        LogUtil.d(TAG, "removeSearchObserver observer: $observer")
        observers.remove(observer)
    }

    override fun executeSearchSuggestion(keyWord: String, city: String) {
        LogUtil.d(TAG, "executeSearchSuggestion keyWord: $keyWord, city: $city")
        Inputtips(contextWeakReference.get(), InputtipsQuery(keyWord, city)).apply {
            setInputtipsListener(this@SearchServiceImpl)
            requestInputtipsAsyn()
        }
    }

    override fun onGetInputtips(p0: MutableList<Tip>?, p1: Int) {
        observers.forEach {
            it.onSearchSuggest(convertSuggestionResult(p0))
        }
    }

    private fun convertSuggestionResult(result: List<Tip>?) =
        result?.map { SearchSuggestInfo(it.name, it.address) }
}